package com.teradata.bigdata.iop.controller;

import com.teradata.bigdata.iop.common.DateTypeEditor;
import com.teradata.bigdata.iop.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.beans.PropertyEditorSupport;
import java.util.Date;

/**
 * @Project:
 * @Description:
 * @Version 1.0.0
 * @Throws SystemException:
 * @Author: <li>2019/1/8/008 Administrator Create 1.0
 * @Copyright ©2018-2019 al.github
 * @Modified By:
 */
@Slf4j
@RestController
public class BaseController {

    @ExceptionHandler
    public R handle(HttpServletRequest request, Exception ex) {
        log.error(ex.getMessage());
        return R.error().put("data",ex.getMessage());
    }

    /**
     * 初始化数据绑定 . <br/>
     * 1. 将所有传递进来的String进行HTML编码，防止XSS攻击.<br/>
     * 2. 将字段中Date类型转换为String类型.
     */
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        /**
         * String类型转换，将所有传递进来的String进行HTML编码，防止XSS攻击.
         */
        binder.registerCustomEditor(String.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
            }

            @Override
            public String getAsText() {
                Object value = getValue();
                return value != null ? value.toString() : "";
            }
        });
        /**
         * date类型转换
         */
        binder.registerCustomEditor(Date.class, new DateTypeEditor());
    }
}
